#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright [Gtlions Lai].
# Create Date:
# Update Date:
__authors__ = '"Gtlions Lai" <gtlions.l@qq.com>'
"""Function for GreenPlum DB tables partitions manager - add partitions.

Add tables partitions.

  ClassFoo: None.
  functionBar(): None.
"""

import sys
import os
import platform
import colorama

if platform.system() == 'Windows' or platform.system() == 'Darwin':
    from psycopg2 import *
elif platform.system() == 'Linux':
    from pygresql.pgdb import *
import datetime
import dsn

pf = '/tmp/collect_tables_size_info.pid'
if os.path.exists(pf):
    print 'processing... , exit it!'
    sys.exit()
else:
    os.system('touch ' + pf)

db = connect(host=dsn.host, database=dsn.database, user=dsn.user, password=dsn.password)
cur = db.cursor()
ctime = datetime.datetime.now()
sql = "select schemaname,tablename,tableowner from pg_tables a where a.schemaname not like 'pg_temp%' and a.schemaname not in ('gp_toolkit','information_schema','pg_catalog','gpmg')"
cur.execute(sql)
try:
    for ret in cur.fetchall():
        v_schemaname = ret[0]
        v_tablename = ret[1]
        v_tableowner = ret[2]
        v_object = v_schemaname + "." + v_tablename
        try:
            cur.execute("select pg_total_relation_size('" + v_object + "');")
            v_totalsize = cur.fetchone()[0]
            cur.execute(
                "insert into gpmg.table_size_info (ctime,schemaname,tablename,tableowner,totalsize) values(%s,%s,%s,%s,%s)",
                (ctime, v_schemaname, v_tablename, v_tableowner, v_totalsize))
            db.commit()
        except Exception, e:
            db.commit()
            print 'error'
            continue
except Exception, e:
    pass
finally:
    db.commit()
    db.close()
    os.system('rm -rf ' + pf)
